package com.xbts.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.core.domain.entity.SysUser;
import com.xbts.common.enums.ShoppingCarEnums;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.*;
import com.xbts.common.utils.list.ListUtils;
import com.xbts.system.domain.CnCloudMarket;
import com.xbts.system.domain.CnUserCloudServersRelation;
import com.xbts.system.domain.dto.CnOrderItemReviewDTO;
import com.xbts.system.domain.vo.CnOrderItemReviewVO;
import com.xbts.system.domain.vo.CnOrderStatisticsVO;
import com.xbts.system.enums.OrderStatusEnum;
import com.xbts.system.mapper.SysUserMapper;
import com.xbts.system.service.ICnCloudMarketService;
import com.xbts.system.service.ICnUserCloudServersRelationService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbts.system.mapper.CnOrderItemMapper;
import com.xbts.system.domain.CnOrderItem;
import com.xbts.system.service.ICnOrderItemService;

/**
 * 子订单Service业务层处理
 * 
 * @author xbts
 * @date 2023-08-03
 */
@Service
public class CnOrderItemServiceImpl  extends ServiceImpl<CnOrderItemMapper, CnOrderItem> implements ICnOrderItemService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ICnCloudMarketService cloudMarketService;

    @Autowired
    private ICnUserCloudServersRelationService cnUserCloudServersRelationService;

    /**
     * 查询子订单列表
     *
     * @param cnOrderItem 子订单
     * @return 子订单
     */
    @Override
    public List<CnOrderItem> selectCnOrderItemList(CnOrderItem cnOrderItem) {
        QueryWrapper<CnOrderItem> queryWrapper = getCnOrderItemQueryWrapper(cnOrderItem);
        queryWrapper.orderByDesc("coi.create_time");
        return baseMapper.queryList(queryWrapper);
    }


    @Override
    public CnOrderStatisticsVO statisticsList(CnOrderItem cnOrderItem) {
        QueryWrapper<CnOrderItem> queryWrapper = getCnOrderItemQueryWrapper(cnOrderItem);
        List<String> lst = new ArrayList<>(2);
        lst.add(OrderStatusEnum.FAIL.name());
        lst.add(OrderStatusEnum.IN_PROGRESS.name());
        queryWrapper.notIn("coi.order_status", lst);
        CnOrderStatisticsVO statisticsList = baseMapper.statisticsList(queryWrapper);

        QueryWrapper<CnUserCloudServersRelation> transactionNumQueryWrapper = getTransactionNumQueryWrapper(cnOrderItem);
        long count = baseMapper.getTransactionNum(transactionNumQueryWrapper);
        statisticsList.setTransactionNum((double) count);
        return statisticsList;
    }

    private QueryWrapper<CnUserCloudServersRelation> getTransactionNumQueryWrapper(CnOrderItem cnOrderItem) {
        QueryWrapper<CnUserCloudServersRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(cnOrderItem.getCreateBy()), "su.nick_name", cnOrderItem.getCreateBy());
        if (StringUtils.isNotNull(cnOrderItem.getParams())) {
            Map<String, Object> map =  cnOrderItem.getParams();
            if (null != map.getOrDefault("startTime", "")
                    && StringUtils.isNotEmpty(map.getOrDefault("startTime", "") + "")) {
                // 处理开始时间
                String startTime = String.valueOf(map.get("startTime"));
                if("year".equals(map.get("type"))){
                    startTime = startTime.substring(0, 4) + "-01-01 00:00:00";
                    queryWrapper.ge("cucsr.create_time", startTime);
                } else {
                    queryWrapper.ge("cucsr.create_time", map.get("startTime") + " 00:00:00");
                }
            }
            if (null != map.getOrDefault("endTime", "")
                    && StringUtils.isNotEmpty(map.getOrDefault("endTime", "") + "")) {
                // 处理结束时间
                String endTime = String.valueOf(map.get("endTime"));
                endTime = DateUtils.getLastTime(endTime, String.valueOf(map.get("type")));
                queryWrapper.le("cucsr.create_time", endTime);
            }
        }
        return queryWrapper;
    }

    @NotNull
    private QueryWrapper<CnOrderItem> getCnOrderItemQueryWrapper(CnOrderItem cnOrderItem) {
        QueryWrapper<CnOrderItem> queryWrapper = new QueryWrapper<>();
        if(!SecurityUtils.isManager()){
            queryWrapper.eq("coi.user_id", SecurityUtils.getUserId());
        }
        if (StringUtils.isNotNull(cnOrderItem.getParams())) {
            Map<String, Object> map =  cnOrderItem.getParams();
            if (null != map.getOrDefault("startTime", "")
                    && StringUtils.isNotEmpty(map.getOrDefault("startTime", "") + "")) {
                // 处理开始时间
                String startTime = String.valueOf(map.get("startTime"));
                if("year".equals(map.get("type"))){
                    startTime = startTime.substring(0, 4) + "-01-01 00:00:00";
                    queryWrapper.ge("coi.create_time", startTime);
                } else {
                    queryWrapper.ge("coi.create_time", map.get("startTime") + " 00:00:00");
                }
            }
            if (null != map.getOrDefault("endTime", "")
                    && StringUtils.isNotEmpty(map.getOrDefault("endTime", "") + "")) {
                // 处理结束时间
                String endTime = String.valueOf(map.get("endTime"));
                endTime = DateUtils.getLastTime(endTime, String.valueOf(map.get("type")));
                queryWrapper.le("coi.create_time", endTime);
            }
        }
        if (StringUtils.isNotEmpty(cnOrderItem.getCreateBy())) {
            queryWrapper.like("su.nick_name", cnOrderItem.getCreateBy());
        }
        queryWrapper.eq(StringUtils.isNotNull(cnOrderItem.getUserId()), "coi.user_id", cnOrderItem.getUserId());
        if(StringUtils.isNotNull(cnOrderItem.getShoppingCarEnums())) {
            queryWrapper.eq("coi.shopping_car_enums", cnOrderItem.getShoppingCarEnums().name());
        }
        queryWrapper.notIn(StringUtils.isNotEmpty(cnOrderItem.getContractStatus()),"coi.contract_status", "1", "2" );
        queryWrapper.ne(StringUtils.isNotEmpty(cnOrderItem.getInvoicing()), "coi.invoicing", cnOrderItem.getInvoicing());
        queryWrapper.eq(StringUtils.isNotNull(cnOrderItem.getOrderStatus()), "coi.order_status", cnOrderItem.getOrderStatus());
        queryWrapper.like(StringUtils.isNotEmpty(cnOrderItem.getSn()), "coi.sn", cnOrderItem.getSn());
        return queryWrapper;
    }

    /**
     * 查询子订单
     *
     * @param orderItemId 子订单主键
     * @return 子订单
     */
    @Override
    public CnOrderItem selectCnOrderItemByOrderItemId(String orderItemId) {
        return getById(orderItemId);
    }

    /**
     * 新增子订单
     *
     * @param cnOrderItem 子订单
     * @return 结果
     */
    @Override
    public boolean insertCnOrderItem(CnOrderItem cnOrderItem) {
        cnOrderItem.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        return save(cnOrderItem);
    }

    /**
     * 修改子订单
     *
     * @param cnOrderItem 子订单
     * @return 结果
     */
    @Override
    public boolean updateCnOrderItem(CnOrderItem cnOrderItem) {
        cnOrderItem.setUpdateBy(SecurityUtils.getUserId().toString());
        cnOrderItem.setUpdateTime(DateUtils.getNowDate());
        return updateById(cnOrderItem);
    }

    /**
     * 批量删除子订单
     *
     * @param orderItemIds 需要删除的子订单主键
     * @return 结果
     */
    @Override
    public boolean deleteCnOrderItemByOrderItemIds(List<String> orderItemIds) {
        return removeBatchByIds(orderItemIds);
    }

    /**
     * 删除子订单信息
     *
     * @param orderItemId 子订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public boolean deleteCnOrderItemByOrderItemId(String orderItemId) {
      return removeById(orderItemId);
    }

    @Override
    public List<CnOrderItemReviewVO> reviewList(CnOrderItemReviewDTO orderItemReviewDTO) {
        if (StringUtils.isNull(orderItemReviewDTO.getShoppingCarEnums())){
            throw new ServiceException("购物车类型不能为空！");
        }
        return baseMapper.reviewList(orderItemReviewDTO);
    }
}
